package com.dynamo.transport.network.practise.channel;

import java.net.SocketAddress;

/**
 * @author duanyimiao
 * @create 2018-11-17 10:08 AM
 * @description Channel相关的门面类
 **/
public class Channels {

    /**
     * 使用该pipeline业务并不需要自己new ChannelPipeline具体实现，只需要调用该方法，这样如果想要换一种实现则只需要改该方法即可
     * @return
     */
    public static ChannelPipeline getPipeline(){
        return new DefaultChannelPipeline();
    }

    public static void bind(ChannelPipeline pipeline,Channel channel) {
        channel.getPipeline().sendDownstream(new ChannelStateEvent(pipeline, channel, Channel.BIND));
    }

    //当创建新的channel时发一个open事件到UpstreamHandler进行处理
    public static void fireChannelOpen(ChannelPipeline pipeline,Channel channel){
        channel.getPipeline().sendUpstream(new ChannelStateEvent(pipeline,channel,Channel.OPEND));
    }

    //处理从channel中获取的数据
    public static void fireMessageReceived(ChannelPipeline pipeline,Channel channel,Object msg){
        channel.getPipeline().sendUpstream(new DefaultMessageEvent(pipeline,channel,msg));
    }

    //client将要尝试连接server
    public static void connect(ChannelPipeline pipeline,Channel channel){
        channel.getPipeline().sendDownstream(new ChannelStateEvent(pipeline,channel,Channel.CONNECT));
    }

    //client已经和server建立连接
    public static void fireChannelConnected(ChannelPipeline pipeline,Channel channel){
        channel.getPipeline().sendUpstream(new ChannelStateEvent(pipeline,channel,Channel.CONNECTED));
    }

    //write msg to channel
    public static void write(ChannelPipeline pipeline,Channel channel,Object msg){
        channel.getPipeline().sendDownstream(new DefaultMessageEvent(pipeline,channel,msg));
    }

}
